package com.clhbolg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.clhbolg.domain.ArticleTag;
import com.clhbolg.mapper.ArticleTagMapper;
import com.clhbolg.model.dto.TagAdminDTO;
import com.clhbolg.model.dto.TagDTO;
import com.clhbolg.model.vo.request.ConditionVO;
import com.clhbolg.model.vo.request.TagVO;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.clhbolg.domain.bo.TagBo;
import com.clhbolg.domain.vo.TagVo;
import com.clhbolg.domain.Tag;
import com.clhbolg.mapper.TagMapper;
import com.clhbolg.service.ITagService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 标签Service业务层处理
 *
 * @author cailinhu
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
@DS("slave")
public class TagServiceImpl implements ITagService {

    private final TagMapper baseMapper;

    @Resource
    private ArticleTagMapper articleTagMapper;

    /**
     * 查询标签
     */
    @Override
    public TagVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询标签列表
     */
    @Override
    public TableDataInfo<TagVo> queryPageList(TagBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Tag> lqw = buildQueryWrapper(bo);
        Page<TagVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询标签列表
     */
    @Override
    public List<TagVo> queryList(TagBo bo) {
        LambdaQueryWrapper<Tag> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<TagVo> queryList(String keyWords) {
        TagBo tagBo = new TagBo();
        tagBo.setTagName(keyWords);
        List<TagVo> tagVos = this.queryList(tagBo);
        return tagVos;
    }

    private LambdaQueryWrapper<Tag> buildQueryWrapper(TagBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Tag> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTagName()), Tag::getTagName, bo.getTagName());
        lqw.eq(bo.getCreateTime() != null, Tag::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, Tag::getUpdateTime, bo.getUpdateTime());
        return lqw;
    }

    /**
     * 新增标签
     */
    @Override
    public Boolean insertByBo(TagBo bo) {
        Tag add = BeanUtil.toBean(bo, Tag.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改标签
     */
    @Override
    public Boolean updateByBo(TagBo bo) {
        Tag update = BeanUtil.toBean(bo, Tag.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Tag entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除标签
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            Long count = articleTagMapper.selectCount(Wrappers.lambdaQuery(ArticleTag.class).in(ArticleTag::getTagId, ids));
            if (count>0)
                throw new GlobalException("被删除的标签已经被引用");




        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TagAdminDTO> listTagsAdmin(ConditionVO vo, PageQuery pageQuery) {
        Page<TagAdminDTO> tags=baseMapper.listTagsAdmin(vo,pageQuery.build());
        return TableDataInfo.build(tags);
    }

    @Override
    public void saveOrUpdate(TagVO tagVO) {
        LambdaQueryWrapper<Tag> wrapper = Wrappers.lambdaQuery(Tag.class).eq(Tag::getTagName, tagVO.getTagName());
        Tag tag = baseMapper.selectOne(wrapper);
        if (Objects.nonNull(tag)&&tag.getTagName().equals(tagVO.getTagName())){
               throw  new GlobalException("分类名称已经存在");
        }
        Tag convert = Convert.convert(Tag.class, tagVO);
        baseMapper.insertOrUpdate(convert);
    }

    @Override
    public List<TagDTO> listTopTenTags() {
        return baseMapper.listTopTenTags();
    }

    @Override
    public List<TagDTO> getAllTags() {
        List<TagDTO> list= baseMapper.getAllArticleTags();
        return list;
    }
}
